package org.wx.herostory.services.util;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @description: 广播
 * @author: wangxun
 * @createDate: 2021/3/1
 * @version: 1.0
 */
public final class Broadcaster {
    /**
     * 信道组, 注意这里一定要用 static,
     * 否则无法实现群发
     */
    static private final ChannelGroup _channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 私有构造器
     */
    private Broadcaster() {
    }

    /**
     * 添加信道
     * @param channel
     */
    static public void addChannel(Channel channel){
        if(channel != null)
        _channelGroup.add(channel);
    }

    /**
     * 删除信道
     * @param channel
     */
    static public void removeChannel(Channel channel){
        if(channel != null)
        _channelGroup.remove(channel);
    }

    /**
     * 广播消息
     * @param msg
     */
    static public void broadcast(Object msg){
        if(msg != null)
        _channelGroup.writeAndFlush(msg);
    }

}
